import React from 'react';
import { Select } from 'antd';
import { OptionData } from 'rc-select/lib/interface';
import { isEqual } from 'lodash';

import { Action, Config } from '../../types';
import { setField } from '../../store/actions';

const RuleFields: React.FC<{
  className?: string,
  config: Config,
  options: OptionData[],
  field?: string,
  path: string,
  onChange: (action: Action) => void,
}> = React.memo((props) => {
  const { className, config, options, field, path, onChange } = props;
  return (
    <Select
      className={className}
      size={config.settings.size}
      placeholder={config.settings.fieldSelectPlaceholder}
      showArrow={!config.settings.readonly}
      style={{pointerEvents: config.settings.readonly ? 'none' : 'auto'}}
      options={options}
      value={field}
      onChange={(value) => onChange(setField(value as string, path as string))}
    />
  );
}, (prevProps, nextProps) => {
  if (isEqual(nextProps.config, prevProps.config)) {
    if (!isEqual(nextProps.options, prevProps.options)) {
      return false;
    }
    if (!isEqual(nextProps.field, prevProps.field)) {
      return false;
    }
    return true;
  } else {
    return false;
  }
});

export default RuleFields;
